//
//  talkSecondStepVC.m
//  SQLiteTesting
//
//  Created by kitinat on 2/4/13.
//  Copyright (c) 2013 EGA. All rights reserved.
//

#import "talkSecondStepVC.h"
#import "ARC_DB.h"
#import "UIViewController+MJPopupViewController.h"
#import "showFileVC.h"
#import "EGAAppDelegate.h"
#import "EGAEmployeeInfo.h"
#import <QuartzCore/QuartzCore.h>
#import "SVPullToRefresh.h"
#import "EGAUtility.h"

@interface talkSecondStepVC ()

@end

@implementation talkSecondStepVC

@synthesize tblTalkSecondStep;
@synthesize tfTalkSecondStep;

@synthesize DocID;
@synthesize EmpID;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


NSArray * arrTalk;


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    [tfTalkSecondStep becomeFirstResponder];
    
    [self setTextViewAsTextField];
    
    [self addInfiniteScrolling];
    
    ARC_DB * DB = [[ARC_DB alloc]init];
    
    if ([DB isHasTalkLV2InDB:DocID] && ![DB internetConnected])
    {
        [self alertNotConnect];
        arrTalk = [DB getTalkLV2:DocID];
        [tblTalkSecondStep reloadData];
        [self scrollTableToButtom];
    }
    else
    {
        [self refresh];
    }
}


-(void)viewWillDisappear:(BOOL)animated
{
    [tfTalkSecondStep resignFirstResponder];
}

-(void)setTextViewAsTextField
{
    tfTalkSecondStep.layer.cornerRadius = 10;
    [tfTalkSecondStep.layer setBorderColor:[[[UIColor grayColor] colorWithAlphaComponent:0.5] CGColor]];
    [tfTalkSecondStep.layer setBorderWidth:2.0];
    tfTalkSecondStep.clipsToBounds = YES;
}

-(void)refresh
{
    ARC_DB * DB = [[ARC_DB alloc]init];
    if([DB internetConnected])
    {
        [DB saveTalkLV2:DocID EmpID:EmpID];
        arrTalk = [DB getTalkLV2:DocID];
        [tblTalkSecondStep reloadData];
    }
    else
    {
        [self alertNotConnect];
    }
    //[self scrollTableToButtom];

}

-(void)alertNotConnect
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ไม่สามารถเชื่อมต่อกับเซิฟเวอร์"
                                                    message:@"ทำให้ไม่สามารถอัพเดทข้อมูล"
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
}


-(void)addInfiniteScrolling
{
    [self.tblTalkSecondStep addInfiniteScrollingWithActionHandler:^{
        
        int64_t delayInSeconds = 2;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self refresh];
            [self scrollTableToButtom];
            [self.tblTalkSecondStep.infiniteScrollingView stopAnimating];
        });
    }];
}








- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
    return [arrTalk count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    // นำ dic ใน array ในแต่ละ row มาโชว์ใน tableview
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    cell = [[UITableViewCell alloc]init];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle : UITableViewCellStyleSubtitle
                                      reuseIdentifier : @"Cell"];
    }
    
    NSDictionary*dicForEachRow = [arrTalk objectAtIndex:indexPath.row];
    
    UITextView *l1  =[[UITextView alloc]initWithFrame:CGRectMake(20, 50, 688,100)];
    UILabel *l2     =[[UILabel alloc]initWithFrame:CGRectMake(200,10,528,30)];
    UILabel *l3     =[[UILabel alloc]initWithFrame:CGRectMake(0,10,190,30)];
    
    
    l1.textColor = [UIColor darkGrayColor];
    l2.textColor = [UIColor darkGrayColor];
    l3.textColor = [UIColor darkGrayColor];
    
    
    l3.backgroundColor = [UIColor colorWithRed:228/255.0 green: 226/255.0 blue:214/255.0 alpha:1];
    l2.backgroundColor = [UIColor colorWithRed:228/255.0 green: 226/255.0 blue:214/255.0 alpha:1];
    
    
    l1.editable = NO;
    l2.textAlignment = UITextAlignmentRight;
    l3.textAlignment = UITextAlignmentLeft;
    
    
    l1.text =   [NSString stringWithFormat:@"\"  %@  \"",   [dicForEachRow objectForKey:@"Talk_Text"]];
    l2.text =   [NSString stringWithFormat:@"โดย : %@    ",     [dicForEachRow objectForKey:@"Post_By"]];
    EGAUtility * Util = [[EGAUtility alloc]init];
    NSString *TimeStamp = [Util getDateTh:([dicForEachRow objectForKey:@"TimeStamp"])];
    l3.text =   [NSString stringWithFormat:@"    เมื่อ : %@",     TimeStamp];
    
    //gen showfile button
    NSString *strList_File_ID =   [NSString stringWithFormat:@"%@",[dicForEachRow objectForKey:@"List_File_ID"]];
    NSArray * arrList_File_ID = [strList_File_ID componentsSeparatedByString:@"|"];
    NSString *strList_File_Name =   [NSString stringWithFormat:@"%@",[dicForEachRow objectForKey:@"List_File_Name"]];
    NSArray * arrList_File_Name = [strList_File_Name componentsSeparatedByString:@"|"];
    
    if (![strList_File_ID isEqualToString:@""])
    {
        for(int i = 0; i <= [arrList_File_ID count]-1 ; i++)
        {NSLog(@"%@",arrList_File_ID[i]);
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setFrame:CGRectMake((i*110)+20 ,150,100,50)];
            [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
            [button setTitle:[NSString stringWithFormat:@" %@", arrList_File_Name[i]] forState:UIControlStateNormal];
            
            button.titleLabel.font = [UIFont fontWithName:@"Arial" size:14];
            
            [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
            [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
            
            button.accessibilityLabel = [NSString stringWithFormat:@"%@|%@",arrList_File_ID[i],arrList_File_Name[i]];
            
            //set button image
            NSArray     * arrFileInfo           = [button.accessibilityLabel componentsSeparatedByString:@"|"];
            NSString    * fileID                = arrFileInfo[0];
            NSString    * fileNameAndType       = arrFileInfo[1];
            NSArray     * arrFileNameAndType    = [fileNameAndType componentsSeparatedByString:@"."];
            NSString    * fileType              = arrFileNameAndType[   [arrFileNameAndType count]-1   ];
            NSString    *  storeFileName = [NSString stringWithFormat:@"%@%@.%@",@"talk",fileID,fileType];
            UIImage *img ;
            if([self isHasFileWithSavedFileName:storeFileName])
                img = [UIImage imageNamed:@"open.png"];
            else
                img = [UIImage imageNamed:@"save.png"];
            
            [button setImage:img forState:UIControlStateNormal];
            
            [cell.contentView addSubview:button];
        }
    }
    
    
    l1.font = [UIFont fontWithName:@"Arial" size:18];
    l2.font = [UIFont fontWithName:@"Arial" size:20];
    l3.font = [UIFont fontWithName:@"Arial" size:20];
    
    
    [cell.contentView addSubview:l1];
    [cell.contentView addSubview:l2];
    [cell.contentView addSubview:l3];
    return cell;
}

- (void)buttonPressed:(UIButton *)sender
{
    //    NSLog(@"%@",sender.accessibilityLabel);
    //
    //    self.SFVC = [[showFileVC alloc] initWithNibName:@"showFileVC" bundle:nil];
    //
    //    self.SFVC.FileID = sender.accessibilityLabel;
    //
    //    [self.view addSubview:self.SFVC.view];
    
    self.SFVC = [[showFileVC alloc] initWithNibName:@"showFileVC" bundle:nil];
    
    self.SFVC.fileInfo = sender.accessibilityLabel;
    self.SFVC.TalkOrTask = @"talk";
    [self presentPopupViewController:self.SFVC animationType:0 popupType:@"showFileTalk"];
}


-(BOOL)isHasFileWithSavedFileName:(NSString*)savedFileName
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:savedFileName];
    
    //if file not exist in document
    if([fileManager fileExistsAtPath:writablePath])
    {
        return YES;
    }
    else
    {
        return NO;
    }
}


- (IBAction)btnReportTouch:(id)sender {
    

    
    
    
    
 
    UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    spinner.center = CGPointMake(700, 610);
    spinner.hidesWhenStopped = YES;
    [self.view addSubview:spinner];
    [spinner startAnimating];
    

    
    dispatch_queue_t submitTalkSecondQueue = dispatch_queue_create("submitTalkSecond", NULL);
    dispatch_async(submitTalkSecondQueue, ^{
        
        // do our long running process here
        [NSThread sleepForTimeInterval:2];
        
        // do any UI stuff on the main UI thread
        dispatch_async(dispatch_get_main_queue(), ^{

            
            
            
            
            
            
            
            
//            NSString *strreq=[NSString stringWithFormat:@"http://%@talkSecondStepAction.ashx",serviceUrl];
//            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: strreq]];
//            NSString * postTextUTF8 = [tfTalkSecondStep.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//            NSString * empFullNameUTF8 = [[NSString stringWithFormat:@"%@ %@", self.appDelegate.employeeInfo.FirstNameTH,self.appDelegate.employeeInfo.LastNameTH] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//            NSString *post = [NSString stringWithFormat:@"docid=%@&postby=%@&talktext=%@&empid=%@",
//                              DocID, empFullNameUTF8 ,postTextUTF8,EmpID];
//            NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//            NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
//            [request setHTTPMethod:@"POST"];
//            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
//            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//            [request setHTTPBody:postData];
//            [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
            
            /////////////////new
            EGAUtility * Util = [[EGAUtility alloc]init];
            NSString * postTextUTF8 = [tfTalkSecondStep.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSString * empFullNameUTF8 = [[NSString stringWithFormat:@"%@ %@", self.appDelegate.employeeInfo.FirstNameTH,self.appDelegate.employeeInfo.LastNameTH] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSString *post = [NSString stringWithFormat:@"docid=%@&postby=%@&talktext=%@&empid=%@",DocID, empFullNameUTF8 ,postTextUTF8,EmpID];
            NSString *strURL=[NSString stringWithFormat:@"ws=talkSecondStepAction.ashx&%@",post];
            [Util getDataFromService:strURL];
            /////////////////new
            
            [self refresh];
            [self scrollTableToButtom];
            [tfTalkSecondStep setText:@""];
            
            
            
            
            
            

       
            [spinner stopAnimating];
        });
    });
    dispatch_release(submitTalkSecondQueue);

    
    
    
    
    
    
    
}

-(EGAAppDelegate*)appDelegate
{
    return  (EGAAppDelegate*)[[UIApplication sharedApplication] delegate];
}

-(void)scrollTableToButtom
{
    if ([arrTalk count]>0)
    {
        NSIndexPath* ipath = [NSIndexPath indexPathForRow: [arrTalk count]-1 inSection: 0];
        [tblTalkSecondStep scrollToRowAtIndexPath: ipath atScrollPosition: UITableViewScrollPositionTop animated: YES];

    }
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end